package db

import (
	"fmt"
	"strconv"
	log "github.com/golang/glog"
	"github.com/garyburd/redigo/redis"
)

type Group struct {
	Appid int64
	Gid	  int64
	Name  string
	Avatar string
	Desc  string
	Owner int64
	Members int64
}

func (group *Group) Save(conn redis.Conn) bool {
	//获取群ID
	key := fmt.Sprintf("%d_groupid", group.Appid)
	gid, err := redis.Int64(conn.Do("INCR", key))
	if err != nil {
		log.Error("redis INCR err: group.save", err)
		return false
	}
	
	group.Gid = gid
	
	key = fmt.Sprintf("%d_%d_groupbase", group.Appid, group.Gid)
	_, err = conn.Do("HMSET", key, 
		"appid", fmt.Sprintf("%d", group.Appid), 
		"gid", fmt.Sprintf("%d", group.Gid), 
		"name", group.Name, 
		"avatar", group.Avatar, 
		"desc", group.Desc, 
		"owner", fmt.Sprintf("%d", group.Owner),
	)
	if err != nil {
		log.Error("redis HMSET err: group.save", err)
		return false
	}
	
	return true
}

func (group *Group) Get(conn redis.Conn, appid int64, gid int64) *Group {
	key := fmt.Sprintf("%d_%d_groupbase", appid, gid)
	
	ret, err := redis.Strings(conn.Do("HMGET", key, "appid", "gid", "name", "avatar", "desc", "owner"))
	if err != nil {
		log.Error("redis HMGET err: group.get", err)
		return nil
	}
	
	key = fmt.Sprintf("%d_%d_groupmembers", appid, gid)
	count, err := redis.Int64(conn.Do("SCARD", key))
	if err != nil {
		log.Error("redis SCARD err: group.get", err)
	}
	
	owner, _ := strconv.Atoi(ret[5])
	group.Appid = appid
	group.Gid = gid
	group.Name = ret[2]
	group.Avatar = ret[3]
	group.Desc = ret[4]
	group.Owner = int64(owner)
	group.Members = count
	
	return group
}

func AddMember(conn redis.Conn, appid int64, gid int64, uid int64) bool {
	key := fmt.Sprintf("%d_%d_groupmembers", appid, gid)
	
	_, err := conn.Do("SADD", key, uid)
	if err != nil {
		log.Error("redis SADD err: group.addmember", err)
		return false
	}
	
	return true
}

func RemoveMember(conn redis.Conn, appid int64, gid int64, uid int64) bool {
	key := fmt.Sprintf("%d_%d_groupmembers", appid, gid)
	
	_, err := conn.Do("SREM", key, uid)
	if err != nil {
		log.Error("redis SREM err: group.removemember", err)
		return false
	}
	
	return true
}

func Remove(conn redis.Conn, appid int64, gid int64) bool {
	key1 := fmt.Sprintf("%d_%d_groupmembers", appid, gid)
	//删除群信息
	key2 := fmt.Sprintf("%d_%d_groupbase", appid, gid)
	_, err := conn.Do("DEL", key1, key2)
	if err != nil {
		log.Error("redis DEL err:group.remove", err)
		return false
	}
	
	return true
}

func GetMembers(conn redis.Conn, appid int64, gid int64) []int{
	key := fmt.Sprintf("%d_%d_groupmembers", appid, gid)
	ret, err := redis.Ints(conn.Do("SMEMBERS", key))
	if err != nil {
		log.Error("redis SMEMBERS err: group.getmembers", err)
		return nil
	}
	
	return ret
}